package com.yhb.androidcore.network.http;

import android.util.Log;

import com.yhb.androidcore.utils.JsonUtils;

import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by yanghongbing on 16/12/31.
 */

public class HttpUtils {

    private static OkHttpClient httpClient = new OkHttpClient();
    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    public static void sendRequest(IRequest request, Callback callback) {
        if (request == null) {
            return;
        }
        Request.Builder requestBuilder = new Request.Builder().url(request.getUrl());
        Map<String, String> headers = request.getHeaders();
        if (headers != null) {
            requestBuilder.headers(Headers.of(headers));
        }
        requestBuilder.tag(request);
        Log.d(HttpConsts.TAG, "--------Http Request " + request.getRequestId() + "--------");
        Log.d(HttpConsts.TAG, "url: " + request.getUrl());
        Log.d(HttpConsts.TAG, "method: " + request.getMethod());
        Log.d(HttpConsts.TAG, "params:" + request.getParams());
        Log.d(HttpConsts.TAG, "headers: " + request.getHeaders());
        if (request.getMethod().equals("POST")) {
            requestBuilder.method(request.getMethod(), RequestBody.create(JSON, JsonUtils.toJSONString(request.getParams())));
        }
        sendRequest(requestBuilder.build(), callback);
    }

    private static void sendRequest(Request request, Callback callback) {
        Call call = httpClient.newCall(request);
        call.enqueue(callback);
    }

}
